//
//  CookListViewController.m
//  cookBook
//
//  Created by xalo on 16/1/22.
//  Copyright © 2016年 张广斌. All rights reserved.
//
#define kLeft 20

#import "CookListViewController.h"
#import "HTTPhelper.h"
#import "PrefixHeader.pch"
#import "CookListViewCell.h"
#import "WebViewController.h"
#import "Model.h"
#import "PickerView.h"

@interface CookListViewController ()

@property (nonatomic,strong) Model *model;

//当前页数
@property (nonatomic,assign) NSInteger number;

//选择视图
@property (nonatomic,strong) PickerView *pickerView;

//菊花转
@property (nonatomic,strong) MBProgressHUD *HUD;

@end

@implementation CookListViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化number
    self.number = 1;
    
    //初始化菊花转
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    
    //加载数据
    [self setMoreDataWithNumber:self.number];
    
    
    //下拉刷新
    [self dropdownRefresh];
    
    //上拉加载
    [self pullOnLoading];
    
    
    
    // pickerView
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"hand"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(packerAction)];

    
}



- (void)packerAction
{
    //初始化
    self.pickerView = [[PickerView alloc] initWithFrame:[UIScreen mainScreen].bounds PageNumber:84 currentRow:self.number - 1];
    
    //添加到window上
    [[UIApplication sharedApplication].keyWindow addSubview:self.pickerView];
    __weak CookListViewController *weakSelf = self;
    
    //block赋值
    self.pickerView.block = ^(NSInteger page){
        
        //传递选择的页数
        weakSelf.number = page;
        
        //清空数据请求单例中数组中model
        [[HTTPhelper sharedManeger].cookListArray removeAllObjects];
        
        //刷新页面
        [weakSelf.tableView reloadData];
        
        //根据传递的参数请求数据
        [weakSelf setMoreDataWithNumber:weakSelf.number];
        
        //判断数据请求中是否有数据
        if ([HTTPhelper sharedManeger].cookListArray.count != 0) {
            
            //第一行移动至顶端
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            
            [weakSelf.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:(UITableViewScrollPositionTop)];
        }

    };

}

// 下拉刷新
- (void)dropdownRefresh
{
    
    __weak CookListViewController *weakSelf = self;
    
    // 下拉刷新数据
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.number = 1;
        
        // 把数组里面的数据置为空
        [[HTTPhelper sharedManeger].cookListArray removeAllObjects];
        
        [weakSelf setMoreDataWithNumber:weakSelf.number];
        
        // 刷新数据
        [weakSelf.tableView reloadData];
        
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
    }];
    
}



// 上拉加载
- (void)pullOnLoading
{
    __weak CookListViewController *weakSelf = self;
    
    // 上拉加载数据
    self.tableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{

        [weakSelf setMoreDataWithNumber:weakSelf.number];
        
        [weakSelf.tableView reloadData];
        
        // 判断是否大于84,大于84结束
        if (weakSelf.number < 85) {
            
            // 结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            
        }
        else
        {
            weakSelf.HUD.labelText = @"已经到底了";
           
            [weakSelf.view addSubview:weakSelf.HUD];
            [weakSelf.HUD show:YES];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.HUD.removeFromSuperViewOnHide = YES;
                [weakSelf.HUD hide:YES];
                
            });
            // 结束
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        
    }];

}


// 请求更多网络数据
- (void)setMoreDataWithNumber:(NSInteger)number
{
    if (number < 85) {
        // 添加加载视图
        self.HUD.labelText = @"正在加载";
        
        self.HUD.removeFromSuperViewOnHide = YES;
        
        [self.view addSubview:self.HUD];
        [self.HUD show:YES];
        
        __weak CookListViewController *weakSelf = self;
        
        NSString *string = [NSString stringWithFormat:@"http://ibaby.ipadown.com/api/food/food.show.list.php?keywords=%%E5%%87%%89%%E8%%8F%%9C&p=%ld&pagesize=12",number];
        
        //请求数据
        [[HTTPhelper sharedManeger] fecthCookListGetingSession:^{
            
            [weakSelf.tableView reloadData];
            
            weakSelf.number++;
            
            // 加载视图消失
            weakSelf.HUD.removeFromSuperViewOnHide = YES;
            [weakSelf.HUD hide:YES];
            
        } url:string];
        
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view data source
// 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [[HTTPhelper sharedManeger] countOfCookListArray];
}



// 加载单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CookListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
    Model *model = [[HTTPhelper sharedManeger] cookListArray][indexPath.row];
    
    [cell setContentViewWithModel:model];
    
    return cell;
}



// 点击进入详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewController *webVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"WebVC"];
    
    Model *model = [[HTTPhelper sharedManeger] returnModelWithIndex:indexPath.row];
    
    webVC.model = model;

    [self.navigationController pushViewController:webVC animated:YES];
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
